package com.shengde.jinwawaforleader.model.homePage;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.shengde.jinwawaforleader.R;
import com.shengde.jinwawaforleader.base.BaseActivity;
import com.shengde.jinwawaforleader.bean.User;
import com.shengde.jinwawaforleader.model.myJob.instance_message.Constant;
import com.shengde.jinwawaforleader.network.BaseProtocol;
import com.shengde.jinwawaforleader.network.BasexUtilsProtocol;
import com.shengde.jinwawaforleader.network.protocolbean.ProSchoolMiens;
import com.shengde.jinwawaforleader.network.protocolbean.ProShowClickGood;
import com.shengde.jinwawaforleader.network.protocolbean.ProUploadImg;
import com.shengde.jinwawaforleader.utils.LGImgCompressor;
import com.shengde.jinwawaforleader.views.SchoolMienPopupWindow;
import com.shengde.jinwawaforleader.views.SelectPicPopupWindow;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 编辑自定义界面
 * Created by JYQ on 2017/1/9 0009.
 */
public class EditCustomActivity extends BaseActivity implements LGImgCompressor.CompressListener, CompoundButton.OnCheckedChangeListener {
    private static final String TAG = "EditCustomActivity";
    private static final int TAKE_PICTURE = 1;
    private static final int SELECT_PICTURE = 2;
    private static final int FINSH = 3;
    private SelectPicPopupWindow showPopupWindow; //自定义popuowindow
    private String picName;  //拍摄图片的名字
    private String path = "";
    private RelativeLayout relative_kingarden_name;  //幼儿园名称
    private RelativeLayout relative_cover_picture;  //封面图片
    private RelativeLayout relative_kingraden_address; //幼儿园地址
    private RelativeLayout relative_link_telephone; //联系电话
    private RelativeLayout relative_school_introduce; //校园简介
    private RelativeLayout relative_certificate;  //资质证书
    private RelativeLayout relative_teacher_mien; //教师风采
    private RelativeLayout relative_student_production; //学生作品
    private TextView tv_back;
    private TextView tv_title;
    private TextView fill_add;
    private TextView tv_kingarden_name;
    private TextView tv_kingraden_address;
    private TextView tv_link_telephone;
    private TextView tv_school_introduce;
    private ImageView iv_cover_drawable;  //封面图片
    private CheckBox check_box;   //是否当前显示的
    private boolean isChecked;
    private SchoolMienPopupWindow schoolMienPopupWindow;

    private ProSchoolMiens.SitelistEntity sitelistEntities;
    private String mUrl;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case FINSH:
                    modificationKingardenName(mUrl);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onRoot(Bundle savedInstanceState) {
        setContentView(R.layout.activity_edit_custom);

    }

    @Override
    public void initView() {
        tv_back = (TextView) findViewById(R.id.tv_back);
        tv_title = (TextView) findViewById(R.id.tv_title);
        fill_add = (TextView) findViewById(R.id.fill_add);
        tv_kingarden_name = (TextView) findViewById(R.id.tv_kingarden_name);
        tv_kingraden_address = (TextView) findViewById(R.id.tv_kingraden_address);
        tv_link_telephone = (TextView) findViewById(R.id.tv_link_telephone);
        tv_school_introduce = (TextView) findViewById(R.id.tv_school_introduce);
        relative_kingarden_name = (RelativeLayout) findViewById(R.id.relative_kingarden_name);
        relative_cover_picture = (RelativeLayout) findViewById(R.id.relative_cover_picture);
        relative_kingraden_address = (RelativeLayout) findViewById(R.id.relative_kingraden_address);
        relative_link_telephone = (RelativeLayout) findViewById(R.id.relative_link_telephone);
        relative_school_introduce = (RelativeLayout) findViewById(R.id.relative_school_introduce);
        relative_certificate = (RelativeLayout) findViewById(R.id.relative_certificate);
        relative_teacher_mien = (RelativeLayout) findViewById(R.id.relative_teacher_mien);
        relative_student_production = (RelativeLayout) findViewById(R.id.relative_student_production);
        iv_cover_drawable = (ImageView) findViewById(R.id.iv_cover_drawable);
        check_box = (CheckBox) findViewById(R.id.check_box);

    }

    @Override
    public void initData() {
        sitelistEntities = (ProSchoolMiens.SitelistEntity) getIntent().getSerializableExtra("sitelistEntities");
        tv_title.setText(getString(R.string.edit_custom));
        fill_add.setText(getString(R.string.more_));
        if (sitelistEntities != null) {
            tv_kingarden_name.setText(sitelistEntities.sname);
            tv_kingraden_address.setText(sitelistEntities.address);
            tv_link_telephone.setText(sitelistEntities.tel);
            Glide.with(this).load(BaseProtocol.IMG_BASE + sitelistEntities.img).error(R.drawable.add_photo).into(iv_cover_drawable);
            if (sitelistEntities.remark.length() > 11) {
                tv_school_introduce.setText(sitelistEntities.remark.substring(0, 11) + "...");
            } else {
                tv_school_introduce.setText(sitelistEntities.remark);
            }
            if ("2".equals(sitelistEntities.type)) {
                check_box.setChecked(true);
                isChecked = true;
            }
        }
    }

    @Override
    public void initListener() {
        tv_back.setOnClickListener(this);
        fill_add.setOnClickListener(this);
        relative_kingarden_name.setOnClickListener(this);
        relative_cover_picture.setOnClickListener(this);
        relative_kingraden_address.setOnClickListener(this);
        relative_link_telephone.setOnClickListener(this);
        relative_school_introduce.setOnClickListener(this);
        relative_certificate.setOnClickListener(this);
        relative_teacher_mien.setOnClickListener(this);
        relative_student_production.setOnClickListener(this);
        check_box.setOnCheckedChangeListener(this);

    }

    @Override
    public void onWidgetClick(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                finish();
                break;
            case R.id.relative_kingarden_name:
                Intent intent = new Intent(EditCustomActivity.this, EditSchoolMienActivity.class);
                intent.putExtra("type", "1");
                startActivityForResult(intent, Constant.REQUEST_CODE);
                break;
            case R.id.relative_cover_picture:
                showPopupWindow(view);
                break;
            case R.id.relative_kingraden_address:
                intent = new Intent(EditCustomActivity.this, EditSchoolMienActivity.class);
                intent.putExtra("type", "2");
                startActivityForResult(intent, Constant.REQUEST_CODE);
                break;
            case R.id.relative_link_telephone:
                intent = new Intent(EditCustomActivity.this, EditSchoolMienActivity.class);
                intent.putExtra("type", "3");
                startActivityForResult(intent, Constant.REQUEST_CODE);
                break;
            case R.id.relative_school_introduce:
                intent = new Intent(EditCustomActivity.this, EditSchoolMienActivity.class);
                intent.putExtra("type", "4");
                startActivityForResult(intent, Constant.REQUEST_CODE);
                break;
            case R.id.relative_certificate:
                if (User.getSiteid(EditCustomActivity.this) == null || "".equals(User.getSiteid(EditCustomActivity.this))) {
                    Toast.makeText(EditCustomActivity.this, "请先完善上面信息", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    intent = new Intent(EditCustomActivity.this, EditTeacherMienActivity.class);
                    intent.putExtra("type", "1");
                    intent.putExtra("siteid", User.getSiteid(EditCustomActivity.this));
                    startActivityForResult(intent, Constant.REQUEST_CODE);
                }
                break;
            case R.id.relative_teacher_mien:
                if (User.getSiteid(EditCustomActivity.this) == null || "".equals(User.getSiteid(EditCustomActivity.this))) {
                    Toast.makeText(EditCustomActivity.this, "请先完善上面信息", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    intent = new Intent(EditCustomActivity.this, EditTeacherMienActivity.class);
                    intent.putExtra("type", "2");
                    intent.putExtra("siteid", User.getSiteid(EditCustomActivity.this));
                    startActivityForResult(intent, Constant.REQUEST_CODE);
                }
                break;
            case R.id.relative_student_production:
                if (User.getSiteid(EditCustomActivity.this) == null || "".equals(User.getSiteid(EditCustomActivity.this))) {
                    Toast.makeText(EditCustomActivity.this, "请先完善上面信息", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    intent = new Intent(EditCustomActivity.this, EditTeacherMienActivity.class);
                    intent.putExtra("type", "3");
                    intent.putExtra("siteid", User.getSiteid(EditCustomActivity.this));
                    intent.putExtra("schoolname", sitelistEntities.sname);
                    startActivity(intent);
                }
                break;
            case R.id.fill_add:
                showPopBottom(view);
                break;
        }

    }


    /**
     * 编辑界面  点击更多的弹窗
     *
     * @param view
     */
    private void showPopBottom(View view) {
        schoolMienPopupWindow = new SchoolMienPopupWindow(this, itemOnClick);
        schoolMienPopupWindow.setWidth(getWindowManager().getDefaultDisplay().getWidth() / 3);
        schoolMienPopupWindow.relative_share.setVisibility(View.GONE);
        schoolMienPopupWindow.tv_editor_custom.setText(getString(R.string.save));
        schoolMienPopupWindow.iv_editor_custom.setImageResource(R.drawable.pop_preview);
        schoolMienPopupWindow.tv_editor_link.setText(getString(R.string.preview));
        schoolMienPopupWindow.iv_editor_link.setImageResource(R.drawable.pop_save);
        //设置layout在PopupWindow中显示的位置
        schoolMienPopupWindow.showPopupWindow(view);
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            schoolMienPopupWindow.dismiss();
            switch (v.getId()) {
                case R.id.relative_editor_link:
                    if ("1".equals(User.getType(EditCustomActivity.this))) {
                        if (User.getSchoolMienUrl(EditCustomActivity.this) == null) {
                            Toast.makeText(EditCustomActivity.this, "请先完善下面信息", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        Intent intent = new Intent(EditCustomActivity.this, PreviewSchoolMien.class);
                        intent.putExtra("url", User.getSchoolMienUrl(EditCustomActivity.this));
                        startActivity(intent);
                    } else if ("2".equals(User.getType(EditCustomActivity.this))) {
                        Intent intent = new Intent(EditCustomActivity.this, PreviewSchoolMien.class);
                        intent.putExtra("url", BaseProtocol.SCHOOL_MIEN + User.getSchoolId(EditCustomActivity.this));
                        startActivity(intent);
                    }
                    break;
                case R.id.relative_editor_custom:
                    if (isChecked) {
                        showSaveUrl("2");
                    } else {
                        showSaveUrl("1");
                    }

                    break;
            }
        }
    };

    /**
     * 上传第三方 链接
     *
     * @param mType
     */
    private void showSaveUrl(String mType) {
        RequestParams params = BasexUtilsProtocol.sendHttpRequest(this, "/synopsis/synopsisAdd");
        params.addParameter("type", mType);
        params.addParameter("schoolid", User.getSchoolId(this));
        params.addParameter("sname", sitelistEntities.sname);
        Log.i(TAG, "modificationKingardenName: mUrl = " + mUrl);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProShowClickGood proShowClick = new Gson().fromJson(result, ProShowClickGood.class);
                if (proShowClick.getCode() == 0) {

                    finish();
                    Toast.makeText(EditCustomActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                BasexUtilsProtocol.dialog.dismiss();


            }
        });
    }

    //显示 弹窗
    private void showPopupWindow(View v) {

        showPopupWindow = new SelectPicPopupWindow(this, itemsOnClick);
        showPopupWindow.tv_video_babydiary_share.setText(getString(R.string.take_photo));
        showPopupWindow.tv_video_babydiary_share.setTextColor(Color.parseColor("#067DFF"));
        showPopupWindow.tv_video_babydiary_delete.setTextColor(Color.parseColor("#067DFF"));
        showPopupWindow.tv_look_big_pic.setVisibility(View.GONE);
        showPopupWindow.tv_video_babydiary_delete.setText(getString(R.string.get_phone_picture));
        showPopupWindow.tv_video_babydiary_cancle.setTextColor(Color.parseColor("#067DFF"));

        //设置layout在PopupWindow中显示的位置
        showPopupWindow.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_video_babydiary_share:  //拍摄
                    //先验证手机是否有sdcard
                    String status = Environment.getExternalStorageState();
                    if (status.equals(Environment.MEDIA_MOUNTED)) {
                        try {
                            File dir = new File(Environment.getExternalStorageDirectory() + "/sdcard/cache/");
                            if (!dir.exists()) {
                                dir.mkdirs();
                            }
                            Intent intent = new Intent();
                            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
                            picName = new Date().getTime() + ".jpg";
                            Uri uri = Uri.fromFile(new File(dir, picName));
                            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                            startActivityForResult(intent, TAKE_PICTURE);
                        } catch (ActivityNotFoundException e) {
                            Toast.makeText(EditCustomActivity.this, "没有找到储存目录", Toast.LENGTH_LONG).show();
                        }
                    }
                    showPopupWindow.dismiss();

                    break;
                case R.id.tv_video_babydiary_delete: //手机中获取
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_PICK);
                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                    startActivityForResult(intent, SELECT_PICTURE);
                    showPopupWindow.dismiss();
                    break;
                case R.id.tv_video_babydiary_cancle:
                    showPopupWindow.dismiss();
                    break;
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUEST_CODE) {
            if (resultCode == Constant.SETTING_KINGARDEN_NAME) {
                tv_kingarden_name.setText(data.getExtras().getString("name"));
            } else if (resultCode == Constant.SETTING_KINGARDEN_ADDRESS) {
                tv_kingraden_address.setText(data.getExtras().getString("address"));
            } else if (resultCode == Constant.SETTING_LINK_TELEPHONE) {
                tv_link_telephone.setText(data.getExtras().getString("telephone"));
            } else if (resultCode == Constant.SETTING_SCHOOL_INTRODUCUTION) {
                tv_school_introduce.setText(data.getExtras().getString("introduce"));
            }
        }


        if (requestCode == SELECT_PICTURE) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    Uri uriPath = data.getData();

                    if (!"".equals(uriPath.getAuthority())) {
                        Cursor cursor = getContentResolver().query(uriPath,
                                new String[]{MediaStore.Images.Media.DATA},
                                null, null, null);
                        cursor.moveToFirst();
                        path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    } else {
                        path = uriPath.getPath();
                    }
                    Glide.with(this).load(path).into(iv_cover_drawable);
                    compressImage();

                }
            }
        } else if (requestCode == TAKE_PICTURE) {
            if (resultCode == RESULT_OK) {

                String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/sdcard/cache/" + picName;

                Bitmap bm = BitmapFactory.decodeFile(filePath);

                final File myCaptureFile = new File(filePath);
                try {
                    BufferedOutputStream bos = new BufferedOutputStream(
                            new FileOutputStream(myCaptureFile));
                    /* 采用压缩转档方法 */
                    bm.compress(Bitmap.CompressFormat.JPEG, 60, bos);
                    /* 调用flush()方法，更新BufferStream */
                    bos.flush();
                    /* 结束OutputStream */
                    bos.close();
                    path = myCaptureFile.getAbsolutePath();
                    Glide.with(this).load(path).into(iv_cover_drawable);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 压缩图片
     */
    private void compressImage() {
        LGImgCompressor.getInstance(EditCustomActivity.this).withListener(EditCustomActivity.this).
                starCompress(Uri.fromFile(new File(path)).toString(), 600, 600, 100);

    }

    @Override
    public void onCompressStart() {
        Log.d(TAG, "onCompressStart");
    }

    @Override
    public void onCompressEnd(LGImgCompressor.CompressResult imageOutPath) {
        Log.d(TAG, "onCompressEnd outPath:" + imageOutPath.getOutPath());
        if (imageOutPath.getStatus() == LGImgCompressor.CompressResult.RESULT_ERROR)//压缩失败
            return;

        File file = new File(imageOutPath.getOutPath());
        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.fromFile(file));
            float imageFileSize = file.length() / 1024f;
            Log.i(TAG, "onCompressEnd:imageInfo " + "image info width:" + bitmap.getWidth() + " \nheight:" + bitmap.getHeight() +
                    " \nsize:" + imageFileSize + "kb" + "\nimagePath:" + file.getAbsolutePath());
            path = file.getAbsolutePath();
            Log.i(TAG, "onCompressEnd: imagePath_one = " + file.getAbsolutePath());
            Log.i(TAG, "onCompressEnd: imagePath_two = " + imageOutPath.getOutPath());
            showUploadPic(path);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传图片
     *
     * @param path 压缩后图片的路径
     */
    private void showUploadPic(String path) {

        String url = BaseProtocol.IMG_UPLOAD_HOST;
        RequestParams params = BaseProtocol.getRequestParams(url);
        params.addHeader("User-Agent", "SOHUWapRebot");
        params.addHeader("Accept-Language", "zh-cn,zh;q=0.5");
        params.addHeader("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.7");
        params.addHeader("Connection", "keep-alive");
        params.setMultipart(true);
        params.addBodyParameter("pic", new File(path));
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProUploadImg pro_class_status = new Gson().fromJson(result, ProUploadImg.class);
                Log.i(TAG, "onSuccess: code" + pro_class_status.getCode());
                if (pro_class_status != null && pro_class_status.getCode() == 0) {
                    List<String> mUrlList = pro_class_status.getUrl();
                    if (mUrlList.size() > 0) {
                        mUrl = mUrlList.get(0);
                        Log.i(TAG, "onSuccess: mUrl" + mUrl);
                    }
                    mHandler.sendEmptyMessage(FINSH);

                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.i(TAG, "onError: ex = " + ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    /**
     * 上传图片返回的值  到服务器
     *
     * @param mUrl
     */
    private void modificationKingardenName(String mUrl) {
        RequestParams params = BasexUtilsProtocol.sendHttpRequest(this, "/synopsis/synopsisAdd");
        params.addParameter("type", "2");
        params.addParameter("schoolid", User.getSchoolId(this));
        params.addParameter("img", mUrl);
        Log.i(TAG, "modificationKingardenName: mUrl = " + mUrl);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                ProShowClickGood proShowClick = new Gson().fromJson(result, ProShowClickGood.class);
                if (proShowClick.getCode() == 0) {
                    Toast.makeText(EditCustomActivity.this, "保存成功", Toast.LENGTH_SHORT).show();

                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                BasexUtilsProtocol.dialog.dismiss();


            }
        });
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        this.isChecked = isChecked;
    }
}
